import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Modal } from 'antd';
import { toJS } from 'mobx';
import { Condition, getAdButtons } from '../list/listCondition';
import { WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { WeaRightMenu, WeaTop, WeaTab, WeaErrorPage, WeaTools, WeaAlertPage } from 'ecCom';
// import WorkPlan from "weaWorkplan"
// const WorkPlanCreate = WorkPlan.com.WorkPlanCreate;
import * as Operate from '../../util/Operate';
import BatchShareDialog from '../comp/crm-batch-share';
import SearchAssignDialog from '../dialog/searchAssignDialog';
import { getCustomerNameById } from '../../util/index';
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

@inject('crmSearchQueryStore', 'crmInfoRightmenuStore')
@observer
class SearchQueryResult extends React.Component {
  constructor(props) {
    super(props);
    window._crmTable = {
      reLoad: props.crmSearchQueryStore.reLoad,
    };
    this.state = {
      visible: false,
      visibleCowork: false,
      customerId: '',
      crmArr: [],
      workplanLoaded: false,
      coworkLoaded: false,
    };
  }
  componentDidMount() {
    this.doInit(this.props);

    if (window.weaWorkplan) {
      this.setState({ workplanLoaded: true });
    } else {
      eventRegister.loadModule('f_workplan', () => {
        this.setState({ workplanLoaded: true });
      }, () => {
        // 加载文件失败 的业务处理， 网络超时，没文件之类
        alert('加载日程模块失败，请联系系统管理员！');
      });
    }

    if (window.weaCowork) {
      this.setState({ coworkLoaded: true });
    } else {
      eventRegister.loadModule('f_cowork', () => {
        this.setState({ coworkLoaded: true });
      }, () => {
        // 加载文件失败 的业务处理， 网络超时，没文件之类
        alert('加载协作模块失败，请联系系统管理员！');
      });
    }
  }
  doInit(props) {
    const { location, crmSearchQueryStore } = props;
    const { doSearch, inited, getConditionInfo, initDatas } = crmSearchQueryStore;
    const params = location.query;
    if (params.fromPortal) {
      initDatas(params);
    }
    if (!inited) {
      getConditionInfo(params);
    }
    doSearch(params);
  }
  componentWillReceiveProps(nextProps) {
    const keyOld = this.props.location.key;
    const keyNew = nextProps.location.key;
    // 点击菜单路由刷新组件
    if (keyOld !== keyNew) {
      const { location, crmSearchQueryStore } = nextProps;
      const { doSearch } = crmSearchQueryStore;
      const params = location.query;
      if (params.fromPortal) {
        this.doInit(nextProps);
      } else {
        crmSearchQueryStore.clearStatus();
        doSearch(params);
      }
    }
  }
  componentWillUnmount() {
    const { crmSearchQueryStore } = this.props;
    crmSearchQueryStore.clearStatus();
    crmSearchQueryStore.resetTable();
  }
  render() {
    const { crmSearchQueryStore } = this.props;
    let { title, loading, tableStore, showSearchAd, form, verified, hasRight, reLoad, selectedRowKeys } = crmSearchQueryStore;
    const formParams = form.getFormParams() || {};
    const account = WeaTools.ls.getJSONObj('theme-account');
    title = getLabel(16407, '查询客户');
    let WorkPlanCreate = {};
    if (window.weaWorkplan) {
      WorkPlanCreate = weaWorkplan.com.WorkPlanCreate;
    }
    const currentCrmId = this.state.customerId;
    return (
      <WeaRightMenu
        ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@0m6c4n`}
        datas={this.getRightMenu()}
        onClick={this.onRightMenuClick}
        collectParams={{
          favname: title,
          favouritetype: 4,
          importantlevel: 1,
          objid: -1,
        }}
      >
        <WeaTop
          ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@segpgm`}
          title={title}
          loading={loading}
          icon={<i className="icon-coms-crm" />}
          iconBgcolor="#96358a"
          buttons={this.getTopButtons(this.props.ecId || '')}
          buttonSpace={10}
          showDropIcon
          dropMenuDatas={this.getRightMenu()}
          onDropMenuClick={this.onRightMenuClick}
        >
          <WeaTab
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@ba1gil`}
            buttonsAd={getAdButtons(crmSearchQueryStore, this.props.ecId || '')}
            searchType={['base', 'advanced']}
            searchsBaseValue={formParams.name}
            setShowSearchAd={this.setShowSearchAd}
            hideSearchAd={this.setShowSearchAd}
            searchsAd={
              <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@hd9lyb`} listStore={crmSearchQueryStore} form={form} onEnterSearch={this.onEnterSearch} /></div>
            }
            showSearchAd={showSearchAd}
            onSearch={this.onSearch}
            onSearchChange={this.onSearchChange}
          />
          <WeaTable
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@5hpvtb`}
            comsWeaTableStore={tableStore}
            hasOrder
            needScroll
            register_table={reLoad}
            onOperatesClick={this.onOperatesClick}
            selectedRowKeys={toJS(selectedRowKeys)}
            tableWidth={this.getTableWidth}
          />
          {this.state.workplanLoaded && window.weaWorkplan && (
            <WorkPlanCreate
              ecId={`${this && this.props && this.props.ecId || ''}_WorkPlanCreate@qi956c`}
              type={'create'}// 新建为'create',查看为'preview',编辑edit,共享share
              visible={this.state.visible}// 显隐受控
              doClose={this.setWorkPlanVisisble}// 关闭回调
              onlyClose={this.setWorkPlanVisisble}// 关闭回调,只做关闭操作
              workPlanId={''} // 日程id，1查看日程时用到
              createConditionParams={[]}// 创建的默认值日期和时间,没有传[]
              activeKey={''} // 查看页面显示的面板1是基本信息，7是相关交流
              // changeTab={() => {}}// 查看页面切换面板的回调
              selectUser={account && account.userid}// 新建日程的创建人id
              workPlanTypeOptions={3}// 客户模块的新建日程，普通新建传'',客户新建传3
              crmIDs={this.state.visible && this.state.crmArr}// 通过客户模块新建日程，并自动带出相关客户,[{'id':'','name':''}]
              description={''}
            />
          )}
          {this.state.coworkLoaded && window.weaCowork && window.weaCowork.com && window.weaCowork.com.CreateCowork && this.state.visibleCowork && (
            <window.weaCowork.com.CreateCowork
              ecId={`${this && this.props && this.props.ecId || ''}_undefined@edf3nz`}
              random={Math.random()}
              initAddQuery={
                {
                  relatedType: 'crm',
                  ids: currentCrmId,
                }
              }
              onCancel={() => {
                this.setState({ visibleCowork: false });
              }}
            />)}
        </WeaTop>
      </WeaRightMenu>);
  }
    getTableWidth = (columns) => {
      const showLength = columns.filter(col => col.display == 'true').length;
      return 120 * showLength;// 也支持返回固定值，如果小于100%,不会生效。
    }

    getTopButtons(ecId) {
      const { crmSearchQueryStore } = this.props;
      const { rightMenu, tableStore } = crmSearchQueryStore;
      const { selectedRowKeys } = tableStore;
      const btnArr = [];
      const that = this;
      const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
      rightMenu && rightMenu.length > 0 && toJS(rightMenu).map((m) => {
        m.isTop == '1' && btnArr.length < 4 && btnArr.push(
          <Button
            ecId={`${ecId}_Button@ta7s5o@${m.type}`}
            type="primary"
            disabled={isDisabled && m.isControl == '1'}
            onClick={() => {
              let fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
              if (fn == '') {
                if (m.type == 'BTN_EXPORT') { // 导出Excel
                  // crmSearchQueryStore.crmExport();
                }
              } else {
                fn = Operate.fnJoinPara(fn);
                if (selectedRowKeys) {
                  let ids = '';
                  toJS(selectedRowKeys).map((id) => {
                    ids += `,${id}`;
                  });
                  ids = ids.length > 0 ? ids.substring(1) : ids;
                  fn = Operate.fnJoinPara(fn, ids);
                }
                eval(`Operate.${fn}`);
              }
            }}
          >
            {m.menuName}
          </Button>,
        );
      });
      return btnArr;
    }
    getRightMenu() {
      const { crmSearchQueryStore } = this.props;
      const { rightMenu, tableStore } = crmSearchQueryStore;
      const btnArr = [];
      const { selectedRowKeys } = tableStore;
      const isDisabled = !(selectedRowKeys.length > 0 && `${toJS(selectedRowKeys)}`);
      rightMenu && rightMenu.length > 0 && rightMenu.map((m) => {
        btnArr.push({
          icon: <i className={m.menuIcon} />,
          content: m.menuName,
          disabled: isDisabled && m.isControl == '1',
        });
      });
    	return btnArr;
    }
    onRightMenuClick=(key)=> {
      const { crmSearchQueryStore } = this.props;
      const { rightMenu, tableStore } = crmSearchQueryStore;
      const { selectedRowKeys } = tableStore;
      const that = this;
      rightMenu && rightMenu.length > 0 && rightMenu.map((m, i) => {
        	if (Number(key) == i) {
          let fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
        		if (fn == '') {
            if (m.type == 'BTN_COLUMN') { // 定制列
              crmSearchQueryStore.onShowColumn();
            } else if (m.type == 'BTN_SEARCH') { // 搜索
              crmSearchQueryStore.doSearch();
            }
          } else {
            fn = Operate.fnJoinPara(fn);
	        		if (selectedRowKeys) {
	        			let ids = '';
	        			toJS(selectedRowKeys).map((id) => {
	        				ids += `,${id}`;
	        			});
	        			ids = ids.length > 0 ? ids.substring(1) : ids;
	        			fn = Operate.fnJoinPara(fn, ids);
	        		}
	        		eval(`Operate.${fn}`);
          }
        }
      });
    }
    onOperatesClick=(record, index, operate, flag)=> {
      const { crmSearchQueryStore, crmInfoRightmenuStore } = this.props;
      const _href = operate && operate.href ? operate.href : '';
      const fn = _href.replace('javascript:', '');
      if (flag == '0') { // 新建邮件
        // if(fn != ""){
        //     fn = Operate.fnJoinPara(fn,record.email);
        // }
        // eval("Operate." + fn);
        crmInfoRightmenuStore.addMailMenu(record.randomFieldId);
      }
      if (flag == '1') { // 新建流程
        // if(fn != ""){
        //     fn = Operate.fnJoinPara(fn,record.randomFieldId);
        // }
        // eval("Operate." + fn);
        crmInfoRightmenuStore.addWorkflow(record.randomFieldId);
      }
      if (flag == '2') { // 新建协作
        const coworkStoreMap = window.weaCowork.store && window.weaCowork.store.coworkStoreMap;
        const cowortore = coworkStoreMap && coworkStoreMap.getMapStore(3);
        this.setState({ customerId: record.randomFieldId, visibleCowork: true });
        cowortore && cowortore.setCreateState({ showNewCowork: true, createOrEdit: 0 });
      }
      if (flag == '3') { // 新建日程
        this.getCustomerInfo(record.randomFieldId);
      }
    }
    setWorkPlanVisisble=(bool=false) => {
      this.setState({ visible: bool});
    }
    setShowSearchAd=(bl) => {
      const { crmSearchQueryStore } = this.props;
      crmSearchQueryStore.setShowSearchAd(bl);
    }
    onSearchChange=(v) => {
      const { location, params, crmSearchQueryStore } = this.props;
      if (crmSearchQueryStore.form.has('name')) {
        crmSearchQueryStore.appendFormFields({ name: { value: v } });
      } else {
        crmSearchQueryStore.form.add(v, { key: 'name' });
      }
    }

    onSearch=(v) => {
      const { location, crmSearchQueryStore } = this.props;
      crmSearchQueryStore.doSearch(location.query);
      crmSearchQueryStore.setShowSearchAd(false);
    }
    getCustomerInfo=(customerId) => {
      const crmArr = [];
      WeaTools.callApi('/api/crm/customer/getCrmNamesById', 'GET', { customerIds: customerId }).then((data) => {
        if (data.status == 'success') {
          crmArr.push({ id: customerId, name: data.datas });
          this.setState({ visible: true, crmArr });
        }
      });
      // return crmArr;
    }

    onEnterSearch=() => {
      const { crmSearchQueryStore } = this.props;
      crmSearchQueryStore.doSearch();
      crmSearchQueryStore.setShowSearchAd(false);
    }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@vurmd5`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(SearchQueryResult);
